"""
客户管理路由
"""
import io
from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash, send_file
from flask_login import login_required
from sqlalchemy import func
import xlsxwriter

from app.extensions import db
from app.models.customer import Customer
from app.models.staff import Staff
from app.models.negotiation import Negotiation

customer_bp = Blueprint('customer', __name__, url_prefix='/customer')


@customer_bp.route('/')
@customer_bp.route('/management')
@login_required
def customer_management():
    """客户管理页面"""
    page = request.args.get('page', 1, type=int)
    search_name = request.args.get('search_name', '')
    search_project = request.args.get('search_project', '')
    search_cooperation_ended = request.args.get('search_cooperation_ended', '')
    
    query = Customer.query
    
    if search_name:
        query = query.filter(Customer.name.contains(search_name))
    if search_project:
        query = query.filter(Customer.project_number.contains(search_project))
    if search_cooperation_ended:
        ended = search_cooperation_ended == 'true'
        query = query.filter(Customer.is_cooperation_ended == ended)
    
    customers = query.paginate(page=page, per_page=20, error_out=False)
    
    # 获取下拉选项数据
    project_numbers = db.session.query(Customer.project_number).distinct().all()
    suitable_managers = db.session.query(Staff.name).all()
    
    return render_template('customer/customer_management.html',
                         customers=customers,
                         project_numbers=[p[0] for p in project_numbers if p[0]],
                         suitable_managers=[s[0] for s in suitable_managers],
                         search_name=search_name,
                         search_project=search_project,
                         search_cooperation_ended=search_cooperation_ended)


@customer_bp.route('/add', methods=['POST'])
@login_required
def add_customer():
    """添加客户"""
    try:
        customer = Customer(
            name=request.form.get('name'),
            project_number=request.form.get('project_number'),
            gender=request.form.get('gender'),
            start_date=datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None,
            end_date=datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None,
            suitable_manager=request.form.get('suitable_manager'),
            notes=request.form.get('notes'),
            is_cooperation_ended=request.form.get('is_cooperation_ended') == 'on',
            # 新增字段
            industry=request.form.get('industry', ''),
            contact_person=request.form.get('contact_person', ''),
            contact_phone=request.form.get('contact_phone', ''),
            contact_email=request.form.get('contact_email', ''),
            address=request.form.get('address', ''),
            description=request.form.get('description', '')
        )
        
        # 自动计算合作天数
        customer.calculate_cooperation_days()
        
        db.session.add(customer)
        db.session.commit()
        flash('客户添加成功')
    except Exception as e:
        db.session.rollback()
        flash(f'添加失败: {str(e)}')
    
    return redirect(url_for('customer.customer_management'))


@customer_bp.route('/edit/<int:customer_id>', methods=['POST'])
@login_required
def edit_customer(customer_id):
    """编辑客户"""
    customer = Customer.query.get_or_404(customer_id)
    try:
        customer.name = request.form.get('name')
        customer.project_number = request.form.get('project_number')
        customer.gender = request.form.get('gender')
        customer.start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        customer.end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        customer.suitable_manager = request.form.get('suitable_manager')
        customer.notes = request.form.get('notes')
        customer.is_cooperation_ended = request.form.get('is_cooperation_ended') == 'on'
        customer.updated_at = datetime.utcnow()
        
        # 更新新增字段
        customer.industry = request.form.get('industry', '')
        customer.contact_person = request.form.get('contact_person', '')
        customer.contact_phone = request.form.get('contact_phone', '')
        customer.contact_email = request.form.get('contact_email', '')
        customer.address = request.form.get('address', '')
        customer.description = request.form.get('description', '')
        
        # 自动重新计算合作天数
        customer.calculate_cooperation_days()
        
        db.session.commit()
        flash('客户信息更新成功')
    except Exception as e:
        db.session.rollback()
        flash(f'更新失败: {str(e)}')
    
    return redirect(url_for('customer.customer_management'))


@customer_bp.route('/delete/<int:customer_id>', methods=['POST'])
@login_required
def delete_customer(customer_id):
    """删除客户"""
    customer = Customer.query.get_or_404(customer_id)
    try:
        db.session.delete(customer)
        db.session.commit()
        flash('客户删除成功')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败: {str(e)}')
    
    return redirect(url_for('customer.customer_management'))


@customer_bp.route('/export')
@login_required
def export_customers():
    """导出客户数据"""
    customers = Customer.query.all()
    
    # 创建Excel文件
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet('客户管理')
    
    # 写入表头
    headers = ['客户姓名', '项目序号', '性别', '合作开始时间', '合作结束时间', 
               '合作天数', '适宜项目负责人', '是否结束合作', '所属行业', '联系人',
               '联系电话', '联系邮箱', '地址', '备注']
    
    # 设置表头格式
    header_format = workbook.add_format({
        'bold': True,
        'bg_color': '#D7E4BC',
        'border': 1
    })
    
    for col, header in enumerate(headers):
        worksheet.write(0, col, header, header_format)
    
    # 写入数据
    for row, customer in enumerate(customers, 1):
        worksheet.write(row, 0, customer.name or '')
        worksheet.write(row, 1, customer.project_number or '')
        worksheet.write(row, 2, customer.gender or '')
        worksheet.write(row, 3, customer.start_date.strftime('%Y-%m-%d') if customer.start_date else '')
        worksheet.write(row, 4, customer.end_date.strftime('%Y-%m-%d') if customer.end_date else '')
        worksheet.write(row, 5, customer.cooperation_days or '')
        worksheet.write(row, 6, customer.suitable_manager or '')
        worksheet.write(row, 7, '是' if customer.is_cooperation_ended else '否')
        worksheet.write(row, 8, customer.industry or '')
        worksheet.write(row, 9, customer.contact_person or '')
        worksheet.write(row, 10, customer.contact_phone or '')
        worksheet.write(row, 11, customer.contact_email or '')
        worksheet.write(row, 12, customer.address or '')
        worksheet.write(row, 13, customer.notes or '')
    
    # 调整列宽
    worksheet.set_column('A:N', 15)
    
    workbook.close()
    output.seek(0)
    
    return send_file(
        output,
        as_attachment=True,
        download_name=f'客户管理_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xlsx',
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
